# -*- coding: utf-8 -*-
# בש״ד
#
# Miraflores Blog for Django - Part of the Cuba Libre Project
# Copyright (C) 2009, Joshua "jag" Ginsberg <jag@flowtheory.net>
# 
# Por mi amor, que inspira a mi cada respiración y que echa de Cuba
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.core.urlresolvers import reverse
from django.views.generic import date_based
from django.views.generic import list_detail
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import models as auth
from django.contrib.auth.decorators import permission_required
from django.contrib.comments.models import Comment
from django.utils import simplejson
from miraflores import settings
from miraflores import models as miraflores
from miraflores import akismetlib
from haystack.views import SearchView
from tagging.models import TaggedItem, Tag

def blog_entry_list(request, 
                    template_name='miraflores/blog_entry_list.html'):
    qs = miraflores.BlogEntry.objects.can_be_seen_by_user(request.user)
    return list_detail.object_list(
        request,
        queryset=qs.order_by('-last_updated'),
        template_name=template_name,
        template_object_name='entry_list',
        paginate_by=settings.ENTRIES_PER_PAGE,
        extra_context={'jquery_url': settings.JQUERY_URL})

def blog_entry_list_by_tag(request,
                           tag, 
                           template_name='miraflores/blog_entry_list_by_tag.html'):
    qs = miraflores.BlogEntry.objects.can_be_seen_by_user(request.user)
    qs = TaggedItem.objects.get_by_model(qs, tag)
    return list_detail.object_list(
        request,
        queryset=qs,
        paginate_by=settings.ENTRIES_PER_PAGE,
        template_name=template_name,
        template_object_name='entry_list',
        extra_context={'tag': tag,
                       'jquery_url': settings.JQUERY_URL})

def blog_entry_list_by_category(request,
                                category, 
                                template_name='miraflores/blog_entry_list_by_category.html'):
    category = get_object_or_404(miraflores.Category, slug=category)
    qs = miraflores.BlogEntry.objects.can_be_seen_by_user(request.user)
    qs = qs.filter(categories__id=category.id)
    return list_detail.object_list(
        request,
        queryset=qs,
        paginate_by=settings.ENTRIES_PER_PAGE,
        template_name=template_name,
        template_object_name='entry_list',
        extra_context={'category': category,
                       'jquery_url': settings.JQUERY_URL})

def blog_entry_detail(request,
                      year,
                      month,
                      day,
                      slug,
                      template_name='miraflores/blog_entry_detail.html'):
    qs = miraflores.BlogEntry.objects.can_be_seen_by_user(request.user)
    extra_context= {'jquery_url': settings.JQUERY_URL}
    if 'c' in request.GET:
        try:
            comment_obj = Comment.objects.get(id=request.GET['c'])
        except Comment.DoesNotExist:
            pass
        else:
            if comment_obj.is_public:
                message = u'Your comment has been posted. Thanks!'
            else:
                message = u'Your comment has been held for moderator approval.'
            extra_context['comment_message'] = message
    return date_based.object_detail(
        request,
        queryset=qs,
        year=year,
        month=month,
        day=day,
        date_field='last_updated',
        slug=slug,
        slug_field='slug',
        template_name=template_name,
        month_format='%m',
        extra_context=extra_context
        )

def blog_entry_archive(request,
                       year,
                       month=None,
                       day=None,
                       template_name='miraflores/blog_entry_archive.html'):
    qs = miraflores.BlogEntry.objects.can_be_seen_by_user(request.user)
    extra_context= {'jquery_url': settings.JQUERY_URL}
    if day is not None:
        return date_based.archive_day(request,
                                      year=year, 
                                      month=month, 
                                      day=day, 
                                      queryset=qs, 
                                      date_field='last_updated', 
                                      month_format='%m',
                                      template_object_name='entry',
                                      template_name=template_name,
                                      extra_context=extra_context)
    elif month is not None:
        return date_based.archive_month(request,
                                        year=year, 
                                        month=month, 
                                        queryset=qs, 
                                        date_field='last_updated', 
                                        month_format='%m', 
                                        template_object_name='entry',
                                        template_name=template_name,
                                        extra_context=extra_context)
    else:
        return date_based.archive_year(request,
                                       year=year, 
                                       queryset=qs, 
                                       date_field='last_updated', 
                                       template_object_name='entry',
                                       make_object_list='true',
                                       template_name=template_name,
                                       extra_context=extra_context)

class MirafloresSearchView(SearchView):
    def get_results(self):
        results = super(MirafloresSearchView, self).get_results()
        qs = miraflores.BlogEntry.objects.can_be_seen_by_user(self.request.user)
        results = filter(lambda result: result.object in qs,
                         results)
        return results
    
    def extra_context(self):
        return {'jquery_url': settings.JQUERY_URL}

def blog_search(request, template_name='miraflores/search.html'):
    view_fn = MirafloresSearchView(template=template_name)
    return view_fn(request)

def ajax_tagsearch(request):
    tag = request.GET.get('tag', '')
    if tag:
        tags = map(lambda obj: obj.name,
                   Tag.objects.filter(name__icontains=tag).order_by('name'))
    else:
        tags = []
    return HttpResponse(mimetype='text/javascript',
                        content=simplejson.dumps(tags))

@permission_required('comments.change_comment')
def admin_report_comment_spam(request, comment_id):
    comment_obj = get_object_or_404(Comment, id=comment_id)
    akismetlib.report_comment_as_spam(request, comment_obj)
    return HttpResponseRedirect(reverse('admin:comments_comment_change',
                                        args=(comment_id,)))

@permission_required('comments.change_comment')
def admin_report_comment_not_spam(request, comment_id):
    comment_obj = get_object_or_404(Comment, id=comment_id)
    akismetlib.report_comment_as_ham(request, comment_obj)
    return HttpResponseRedirect(reverse('admin:comments_comment_change',
                                        args=(comment_id,)))
